# app/api/v1/family/blog.py
import logging
from typing import Optional

from fastapi import APIRouter, Body, Query, Path,Depends
from tortoise.expressions import Q

from app.controllers.system.blog import blog_controller
from app.schemas.system.blog import *
from app.utils.request import RequestHandler
from app.utils.app_log import logger
from app.core.auth import get_current_user_required,get_current_superuser
from app.schemas.base.login import JWTPayload

router = APIRouter()

@router.get("/list", summary="获取博客列表")
async def get_blogs(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    title: Optional[str] = Query(None, description="博客标题，用于搜索"),
    type: Optional[str] = Query(None, description="博客类型"),
    status: Optional[str] = Query(None, description="发布状态"),
    current_user: JWTPayload = Depends(get_current_superuser)
):
    """获取博客列表"""
    try:
        q = Q() 
        if title:
            q &= Q(title__contains=title)
        if type:
            q &= Q(type=type)
        if status:
            q &= Q(status=status)

        total, data = await blog_controller.blog_list(page=page, page_size=page_size, q=q)
        return RequestHandler.success_paginated(data=data, total=total, page=page, page_size=page_size)
    except Exception as e:
        logger.error(f"获取博客列表失败: {str(e)}")
        return RequestHandler.server_error(message="获取博客列表失败")

@router.get("/{blog_id}", summary="获取博客详情")
async def get_blog(
    blog_id: int = Path(..., description="博客ID"),
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """获取博客详情"""
    try:
        blog_info = await blog_controller.get_blog_info(blog_id, current_user.user_id)
        return RequestHandler.success(data=blog_info)
    except Exception as e:
        logger.error(f"获取博客详情失败: {str(e)}")
        return RequestHandler.server_error(message="获取博客详情失败")

@router.delete("/{blog_id}", summary="删除博客")
async def delete_blog(
    blog_id: int = Path(..., description="博客ID"),
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """删除博客"""
    try:
        delete_result = await blog_controller.remove_blog(blog_id, current_user.user_id)
        if delete_result:
            return RequestHandler.success(message="博客删除成功")
    except Exception as e:
        logger.error(f"删除博客失败: {str(e)}")
        return RequestHandler.server_error(message="删除博客失败")

@router.post("/create", summary="创建博客")
async def create_blog(
    blog_in: BlogCreate,
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """创建博客"""
    try:
        logger.info(f"创建博客: {blog_in.title}")
        blog_in.user_id = current_user.user_id
        blog = await blog_controller.create_blog(blog_in)
        if blog:
            return RequestHandler.success(message="博客创建成功", data={"id": blog.id})
    except Exception as e:
        logger.error(f"创建博客失败: {str(e)}")
        return RequestHandler.server_error(message="创建博客失败")

@router.put("/{blog_id}", summary="更新博客")
async def update_blog(
    blog_id: int = Path(..., description="博客ID"),
    blog_in: BlogUpdate = None,
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """更新博客"""
    try:
        if blog_in:
            blog_in.id = blog_id
        blog = await blog_controller.update_blog_info(blog_id, blog_in, current_user.user_id)
        if blog:
            return RequestHandler.success(message="博客更新成功")
    except Exception as e:
        logger.error(f"更新博客失败: {str(e)}")
        return RequestHandler.server_error(message="更新博客失败")

@router.put("/{blog_id}/views", summary="增加博客浏览量")
async def increase_blog_views(
    blog_id: int = Path(..., description="博客ID"),
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """增加博客浏览量"""
    try:
        blog = await blog_controller.increase_views(blog_id, current_user.user_id)
        if blog:
            return RequestHandler.success(message="浏览量增加成功")
    except Exception as e:
        logger.error(f"增加博客浏览量失败: {str(e)}")
        return RequestHandler.server_error(message="增加博客浏览量失败")

@router.put("/{blog_id}/like", summary="点赞/取消点赞博客")
async def toggle_blog_like(
    blog_id: int = Path(..., description="博客ID"),
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """点赞/取消点赞博客"""
    try:
        blog = await blog_controller.toggle_like(blog_id, current_user.user_id)
        action = "点赞" if blog.likes > 0 else "取消点赞"
        return RequestHandler.success(message=f"博客{action}成功")
    except Exception as e:
        logger.error(f"点赞博客失败: {str(e)}")
        return RequestHandler.server_error(message="点赞博客失败")